package com.ayu.auth.filter;

import com.ayu.auth.config.RsaKeyProperties;
import com.ayu.auth.pojo.SysUser;
import com.ayu.auth.util.OutPutJson;
import com.ayu.common.pojo.Payload;
import com.ayu.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 徐林玉//作者及
 * @Date: 2021/9/27//完成日期
 * @Description: //
 * @Version: v0.0.1 // 版本信息
 * @Function List: // 主要函数及其功能
 * @Others: // 其它内容的说明
 * @History: // 历史修改记录
 **/

@Slf4j
public class JwtVerifyFilter extends BasicAuthenticationFilter
{

	private RsaKeyProperties rsaKeyProperties;



	public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties rsaKeyProperties)
	{
		super(authenticationManager);
		this.rsaKeyProperties = rsaKeyProperties;

	}

	@Override
	public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
	{
		String header = request.getHeader("Authorization");

		if (header == null || !header.startsWith("Bearer "))
		{
			//如果携带错误的token，则给用户提示请登录！
			chain.doFilter(request, response);
			OutPutJson.success(response, HttpServletResponse.SC_FORBIDDEN, "请登录!");

		} else
		{

			try{

				//如果携带了正确格式的token要先得到token
				String token = header.replace("Bearer ", "");
				//验证token是否正确

				Payload<SysUser> payload = JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), SysUser.class);

				SysUser userInfo = payload.getUserInfo();

				if (userInfo != null)
				{

					UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(userInfo.getUsername(), null, userInfo.getAuthorities());

					SecurityContextHolder.getContext().setAuthentication(authResult);

					chain.doFilter(request,response);

				}

			}catch (Exception e){
				OutPutJson.success(response,HttpServletResponse.SC_UNAUTHORIZED,"token认证失败");
			}




		}
	}
}
